package com.cn.goodsadmin.controller;

import com.cn.goodsadmin.config.BaseConfig;
import com.cn.goodsadmin.po.GoodsIds;
import com.cn.goodsadmin.po.GoodsInfo;
import com.cn.goodsadmin.service.GoodsInfoService;
import com.cn.goodsadmin.util.ErrorMsg;
import com.cn.goodsadmin.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//@CrossOrigin(origins = {"http://10.10.10.143:8020"}, maxAge = 3600)
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@Slf4j
public class GoodsInfoController {

    @Autowired
    GoodsInfoService goodsInfoService;


    //@LoginRequired
    @RequestMapping(value = "/addgoods", method = RequestMethod.POST, produces = "application/json;charset=utf-8",
            consumes = "application/json;charset=utf-8")
    @ResponseBody//表示返回的是个json对象会经过配置文件转换
    public SupplyMap addGoodsInfo(@RequestBody GoodsInfo goodsInfo) {
        SupplyMap supplyMap = new SupplyMap();
        try {
            goodsInfoService.addGoods(goodsInfo);
        } catch (Exception e) {
            log.error("data source error",e);
            supplyMap.setEorrInfo(ErrorMsg.STATUS_DATABASE_ERROR, ErrorMsg.MSG_DATABASE_ERROR);
        }
        return supplyMap;
    }

    @LoginRequired
    @RequestMapping(value = "/updategoods", method = RequestMethod.POST, produces = "application/json;charset=utf-8",
            consumes = "application/json;charset=utf-8")
    @ResponseBody//表示返回的是个json对象会经过配置文件转换
    public SupplyMap updateCoffeeInfo(@RequestBody GoodsInfo goodsInfo) {
        SupplyMap supplyMap = new SupplyMap();
        try {
            goodsInfoService.updateGoods(goodsInfo);
        } catch (Exception e) {
            supplyMap.setEorrInfo(ErrorMsg.STATUS_DATABASE_ERROR, ErrorMsg.MSG_DATABASE_ERROR);
        }
        return supplyMap;
    }

    @LoginRequired
    @RequestMapping(value = "/allgoods",method = RequestMethod.GET,params = {"appid"})
    @ResponseBody//表示返回的是个json对象会经过配置文件转换
    public SupplyMap allCoffeeInfo(int appid){
        SupplyMap supplyMap=new SupplyMap();
        try{
            List<GoodsInfo> goodsInfos=goodsInfoService.getAllGoodsInfo(appid);
            if(goodsInfos!=null){
                supplyMap.put("goodslist",goodsInfos);
            }
        }catch (Exception e){
            supplyMap.setEorrInfo(ErrorMsg.STATUS_DATABASE_ERROR, ErrorMsg.MSG_DATABASE_ERROR);
        }
        return supplyMap;
    }


    @LoginRequired
    @RequestMapping(value = "/deletegoods",method = RequestMethod.POST,produces = "application/json;charset=utf-8",
            consumes = "application/json;charset=utf-8")
    @ResponseBody//表示返回的是个json对象会经过配置文件转换
    public SupplyMap deleteCoffeeInfo(@RequestBody GoodsIds goodsIds){
        SupplyMap supplyMap=new SupplyMap();
        try{
            List<String> ids=goodsIds.getGoodsids();
            goodsInfoService.delete(ids);
        }catch (Exception e){
            supplyMap.setEorrInfo(ErrorMsg.STATUS_DATABASE_ERROR, ErrorMsg.MSG_DATABASE_ERROR);
        }
        return supplyMap;
    }




    @RequestMapping(value = "/upload/{realdic}", method = RequestMethod.POST)
    @ResponseBody
    public SupplyMap upload(@RequestParam(value = "file", required = false) MultipartFile file,@PathVariable String realdic) {
        SupplyMap supplyMap = new SupplyMap();
        try {
            if (file != null) {
                String path = null;// 文件路径
                String type = null;// 文件类型
                String fileName = file.getOriginalFilename();// 文件原名称
                System.out.println("上传的文件原名称:" + fileName);
                type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
                if (type != null) {
                    // 配置的文件目录
                    String realPath = BaseConfig.filePath+realdic;
                    File dir=new File(realPath);
                    if(!dir.exists()){
                        dir.mkdirs();
                    }
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置存放图片文件的路径
                    path = realPath +"/"+trueFileName;
                    System.out.println("存放图片文件的路径:" + path);
                    // 转存文件到指定的路径
                    file.transferTo(new File(path));
                    System.out.println("文件成功上传到指定目录下");
                    String imageUrl= UrlUtil.coverUrl(path);
                    supplyMap.put("imgurl",imageUrl);
                }else{
                    supplyMap.setEorrInfo(ErrorMsg.STATUS_UPLOAD_ERROR, ErrorMsg.MSG_UPLOAD_ERROR);
                }
            } else {
                supplyMap.setEorrInfo(ErrorMsg.STATUS_UPLOAD_ERROR, ErrorMsg.MSG_UPLOAD_ERROR);
            }

        } catch (Exception e) {
            supplyMap.setEorrInfo(ErrorMsg.STATUS_DATABASE_ERROR, ErrorMsg.MSG_DATABASE_ERROR);
        }
        return supplyMap;
    }


    @RequestMapping(value="/uploadfiles/{realdic}",method=RequestMethod.POST)
    @ResponseBody
    private SupplyMap fildUpload(@RequestParam(value="file",required=false) MultipartFile[] file,
                                 @PathVariable String realdic)throws Exception{
        SupplyMap supplyMap=new SupplyMap();
        //获得物理路径webapp所在路径
        List<String> listImagePath=new ArrayList<String>();
        for (MultipartFile mf : file) {
            if(!mf.isEmpty()) {
                //获得文件后缀名称
                String fileName = mf.getOriginalFilename();// 文件原名称
                //获得文件类型（可以判断如果不是图片，禁止上传）
                String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
                if (type != null) {
                    // 配置的文件目录
                    String realPath = BaseConfig.filePath + realdic;
                    File dir = new File(realPath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    String path = realPath +"/"+trueFileName;
                    System.out.println("存放图片文件的路径:" + path);
                    // 转存文件到指定的路径
                    mf.transferTo(new File(path));
                    System.out.println("文件成功上传到指定目录下");
                    String imageUrl= UrlUtil.coverUrl(path);
                    listImagePath.add(imageUrl);
                }
            }
        }
        if(listImagePath.size()>0){
            supplyMap.put("urllist",listImagePath);
        }else{
            supplyMap.setEorrInfo(ErrorMsg.STATUS_UPLOAD_ERROR, ErrorMsg.MSG_UPLOAD_ERROR);
        }
        return supplyMap;
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> downloadFile(String filePath)
            throws IOException {
        log.info("进入下载方法...");
        FileSystemResource file = new FileSystemResource(filePath);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}
